import { useUserStore } from '@/store'
import type { Directive, DirectiveBinding } from 'vue'

function checkPermission(el: HTMLElement, binding: DirectiveBinding<string[]>) {
  // 获取绑定的值，此处为权限
  const { value } = binding

  const { btnPermissions } = useUserStore().userInfo

  if (value && value instanceof Array) {
    // 匹配对应的指令
    const hasPermission = value.some(permission => {
      return btnPermissions.includes(permission)
    })
    if (!hasPermission) {
      el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error('v-has 指令的值必须是数组 例["sys_menu_add","sys_menu_edit"]')
  }
}

export const hasPerm: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding<string[]>) {
    checkPermission(el, binding)
  },

  updated(el: HTMLElement, binding: DirectiveBinding) {
    checkPermission(el, binding)
  }
}
